//
//  SJSpaceStationViewController.m
//  WSL
//
//  Created by CJ on 2017/11/24.
//  Copyright © 2017年 sanjuetech. All rights reserved.
//

#import "SJSpaceStationViewController.h"

#import "SJTreeViewController.h"
#import "SJWordItem.h"
#import "SJExtraItem.h"
#import "SJOneCell.h"
#import "SJCustomLayout.h"
#import "SJTreeApi.h"
#import "SJMovePosApi.h"
#import "SJPublishApi.h"
#import "SJSpaceStationAddApi.h"
#import "SJSpaceStationDelApi.h"
#import "SJSpaceStationCancelApi.h"
#import "SJUnFollowPersonApi.h"
#import "SJFollowPersonApi.h"

#import "JTSImageViewController.h"
#import "JTSImageInfo.h"

#import <JPVideoPlayer/UIView+WebVideoCache.h>
#import <AVFoundation/AVFoundation.h>

#import "SJUploadBar.h"
#import "SJUserInfoItem.h"
#import "SJTreeHeaderView.h"

#import "SJSpaceStationListApi.h"
#import "SJTxtDetailViewController.h"


@interface SJSpaceStationViewController () <UICollectionViewDataSource, UICollectionViewDelegate, SJCustomLayoutDelegate, JTSImageViewControllerAnimationDelegate, JPVideoPlayerDelegate>


////////////////////////////////////

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) int page;

@property (strong, nonatomic) SJCustomLayout *customLayout;

// 视频
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) SJWordItem *selectedItem;
@property (nonatomic, strong) UIView *videoContainer;

@property (nonatomic, strong) UIView *detailImageView;
@property (strong, nonatomic) UILabel *detailLabel;


/////////  navigationBar
@property (nonatomic, strong) SJUserInfoItem *userItem; // 0级词的 owner
@property (nonatomic, strong) UIView *navigationBarView; // 背景
@property (strong, nonatomic) UIButton *displayButton;
@property (nonatomic, copy) NSString *isDisplayTitle;
@property (strong, nonatomic) UIImageView *avatarImageView;
@property (strong, nonatomic) UILabel *nameLabel;

@property (strong, nonatomic) UIButton *deleteButton;
@property (strong, nonatomic) UIButton *chooseButton;

@property (nonatomic, copy) NSString *isChoosing;
@property (nonatomic, strong) NSMutableArray *selectedArray;

@end

@implementation SJSpaceStationViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [SJStatisticTool beginLogPageView:NSStringFromClass([self class])];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [SJStatisticTool endLogPageView:NSStringFromClass([self class])];
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    NSString *imageName = @"guide_cutboard_upload";
    if (812 == SJScreenH) {
        imageName = [NSString stringWithFormat:@"%@-x", imageName];
    }
    
    if ([SJGuideView shouldShowGuider:imageName]) {
        [SJGuideView guideViewWithImageName:imageName];
    }
}

- (void)dealloc {
    SJLogFunc;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.userItem = [SJUserInfoItem modelWithJSON:[SJUserDefaults objectForKey:SJUserInfo]];
    self.isDisplayTitle = @"0";
    self.isChoosing = @"0";
    self.page = 0;
    [self setupUI];
    [self loadNewData];
}

- (void)setupUI {
    
    [self.view addSubview:self.collectionView];
    self.collectionView.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
    
    [self.view addSubview:self.navigationBarView];
    
    if (812 == SJScreenH) {
        self.navigationBarView.sd_layout
        .leftSpaceToView(self.view, SJLayoutFrame(0))
        .topSpaceToView(self.view, SJLayoutFrame(40))
        .heightIs(SJLayoutFrame(50))
        .widthIs(SJScreenW);
    } else {
        self.navigationBarView.sd_layout
        .leftSpaceToView(self.view, SJLayoutFrame(0))
        .topSpaceToView(self.view, SJLayoutFrame(0))
        .heightIs(SJLayoutFrame(50))
        .widthIs(SJScreenW);
    }
    
    [self.view addSubview:self.deleteButton];
    self.deleteButton.sd_layout
    .bottomSpaceToView(self.view, SJLayoutFrame(11))
    .rightSpaceToView(self.view, SJLayoutFrame(20))
    .heightIs(SJLayoutFrame(60))
    .widthIs(SJLayoutFrame(60));
    
}

#pragma mark - getter

- (UIView *)navigationBarView{
    
    if (!_navigationBarView) {
        
        
        _navigationBarView = [UIView new];
        _navigationBarView.backgroundColor = [UIColor clearColor];
        
        // 返回
        UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [backButton setImage:[UIImage imageNamed:@"addtext-icon-return"] forState:UIControlStateNormal];
        [backButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_navigationBarView addSubview:backButton];
        backButton.sd_layout
        .centerYEqualToView(_navigationBarView)
        .leftSpaceToView(_navigationBarView, SJLayoutFrame(10))
        .heightIs(SJLayoutFrame(30))
        .widthIs(SJLayoutFrame(30));
        
        // 词条输入
        UILabel *wordLabel = [UILabel new];
        wordLabel.textColor = SJColorHexString(@"#ffffff");
        wordLabel.font = [UIFont fontWithName:@"Helvetica" size:SJLayoutFrame(17)];
        wordLabel.textAlignment = NSTextAlignmentCenter;
        wordLabel.text = @"剪切板";
        
        [_navigationBarView addSubview:wordLabel];
        wordLabel.sd_layout
        .centerYEqualToView(_navigationBarView)
        .centerXEqualToView(_navigationBarView)
        .heightIs(SJLayoutFrame(27));
        [wordLabel setSingleLineAutoResizeWithMaxWidth:SJScreenW * .5];
        
        [_navigationBarView addSubview:self.chooseButton];
        self.chooseButton.sd_layout
        .centerYEqualToView(_navigationBarView)
        .rightSpaceToView(_navigationBarView, SJLayoutFrame(20))
        .heightIs(SJLayoutFrame(30))
        .widthIs(SJLayoutFrame(60));
        
        
    }
    return _navigationBarView;
}

- (void)backAction {
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (UIButton *)deleteButton {
    
    if (!_deleteButton) {
        
        _deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_deleteButton setImage:[UIImage imageNamed:@"spacestation_bt_delete"] forState:UIControlStateNormal];
        [_deleteButton addTarget:self action:@selector(deleteAction) forControlEvents:UIControlEventTouchUpInside];
        _deleteButton.hidden = YES;
    }
    return _deleteButton;
}
- (void)deleteAction {

    if (self.selectedArray.count == 0) {
        return;
    }
    
    UIView *view = [UIView new];
    view.frame = CGRectMake(0, 0, SJLayoutFrame(156), SJLayoutFrame(118.5));
    
    UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [deleteButton setImage:[UIImage imageNamed:@"spacestation_btn_window_delete_confirm"] forState:UIControlStateNormal];
    [deleteButton addTarget:self action:@selector(deleteConfirm) forControlEvents:UIControlEventTouchUpInside];
    
    [view addSubview:deleteButton];
    deleteButton.sd_layout
    .centerXEqualToView(view)
    .topSpaceToView(view, SJLayoutFrame(22))
    .heightIs(SJLayoutFrame(30))
    .widthIs(SJLayoutFrame(93));
    
    UIButton *cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelButton setImage:[UIImage imageNamed:@"spacestation_btn_window_delete_cancel"] forState:UIControlStateNormal];
    [cancelButton addTarget:self action:@selector(deleteCancel) forControlEvents:UIControlEventTouchUpInside];
    
    [view addSubview:cancelButton];
    cancelButton.sd_layout
    .centerXEqualToView(view)
    .bottomSpaceToView(view, SJLayoutFrame(22))
    .heightIs(SJLayoutFrame(30))
    .widthIs(SJLayoutFrame(93));
    
    [LEEAlert alert].config
    .LeeAddCustomView(^(LEECustomView *custom) {
        // 设置视图对象
        custom.view = view;
    })
    .LeeCornerRadius(SJCornerRadius)
    .LeeHeaderColor(SJColorHexString(@"#00000099"))     //弹框背景颜色
    .LeeBackgroundStyleTranslucent(0)     //屏幕背景半透明样式 参数为透明度
    .LeeClickBackgroundClose(YES)
    .LeeConfigMaxWidth(^CGFloat(LEEScreenOrientationType type) {
        return SJLayoutFrame(156);
    })
    .LeeHeaderInsets(UIEdgeInsetsZero)
    .LeeCloseComplete(^{
        _deleteButton.hidden = YES;
    })
    .LeeShow();
    
    return;
}

- (void)deleteConfirm {
    
    [LEEAlert closeWithCompletionBlock:^{
        
        NSMutableArray *selIDArray = [NSMutableArray array];
        
        for (SJWordItem *item in self.selectedArray) {
            [selIDArray addObject:item.ID];
        }
        
        NSString *jsonString = [selIDArray jsonStringEncoded];
        
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
        parameters[@"ids"] = jsonString;
        
        SJSpaceStationDelApi *api = [[SJSpaceStationDelApi alloc] initWithParameters:parameters];
        [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
            
            if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
                
                self.chooseButton.selected = NO;
                self.isChoosing = @"0";
                [self loadNewData];
            }
            
        } failure:^(YTKBaseRequest *request) {
            
        }];
        
    }];
}

- (void)deleteCancel {
    
    [LEEAlert closeWithCompletionBlock:^{
        
        //如果在关闭后需要做一些其他操作 建议在该Block中进行
    }];
    
}

- (UIButton *)chooseButton {
    
    if (!_chooseButton) {
        
        _chooseButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_chooseButton setImage:[UIImage imageNamed:@"spacestation_bt_edit"] forState:UIControlStateNormal];
        [_chooseButton setImage:[UIImage imageNamed:@"spacestation_bt_cancel"] forState:UIControlStateSelected];
        [_chooseButton addTarget:self action:@selector(chooseAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _chooseButton;
}

- (void)chooseAction {
    
    for (SJWordItem *item in self.dataArray) {
        item.isSelected = NO;
    }
    
    [self.selectedArray removeAllObjects];
    
    self.chooseButton.selected = !self.chooseButton.selected;
    if (self.chooseButton.selected) {
        self.isChoosing = @"1";
        _deleteButton.hidden = NO;
    } else {
        self.isChoosing = @"0";
        _deleteButton.hidden = YES;
    }
    [self.collectionView reloadData];

}

- (UIView *)detailImageView{
    
    if (!_detailImageView) {
        
        _detailImageView = [UIView new];
        _detailImageView.backgroundColor = SJColorHexString(@"#00000090");
        _detailImageView.alpha = 0;
        
        [_detailImageView addSubview:self.detailLabel];
        self.detailLabel.sd_layout.spaceToSuperView(UIEdgeInsetsMake(SJLayoutFrame(9), SJLayoutFrame(13), SJLayoutFrame(9), SJLayoutFrame(50)));
        
    }
    return _detailImageView;
}

- (UILabel *)detailLabel {
    
    if (!_detailLabel) {
        
        _detailLabel = [UILabel new];
        _detailLabel.textColor = SJColorHexString(@"#ffffffff");
        _detailLabel.font = [UIFont systemFontOfSize:SJLayoutFrame(12)];
        _detailLabel.textAlignment = NSTextAlignmentLeft;
        _detailLabel.numberOfLines = 0;
        
    }
    return _detailLabel;
}

- (NSMutableArray *)dataArray {
    
    if (!_dataArray) {
        
        _dataArray = [[NSMutableArray alloc] init];
        
    }
    return _dataArray;
}

- (NSMutableArray *)selectedArray {
    
    if (!_selectedArray) {
        
        _selectedArray = [[NSMutableArray alloc] init];
        
    }
    return _selectedArray;
}

- (UICollectionView *)collectionView {
    
    if (!_collectionView) {
        
        // 首页
        self.customLayout = [[SJCustomLayout alloc] init];
        self.customLayout.delegate = self;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:self.customLayout];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.contentInset = UIEdgeInsetsMake(SJLayoutFrame(57), 0, 0, 0);
        
        [_collectionView registerClass:[SJOneCell class] forCellWithReuseIdentifier:NSStringFromClass([SJOneCell class])];
        
        // header
        _collectionView.mj_header = [SJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        // footer
        _collectionView.mj_footer = [SJDIYFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        
        _collectionView.allowsMultipleSelection = YES;
        
    }
    
    return _collectionView;
}
#pragma mark - SJCustomLayoutDelegate

- (CGRect)collectionView:(UICollectionView *)collectionView layout:(SJCustomLayout *)layout frameOfItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SJWordItem *item = self.dataArray[indexPath.item];
    
    int lNum = [item.l intValue];
    int tNum = [item.t intValue];
    int wNum = [item.w intValue];
    int hNum = [item.h intValue];
    
    
    CGFloat x = lNum * SJItemWH + (lNum + 1) * SJMargin;
    CGFloat y = tNum * SJItemWH + (tNum + 0) * SJMargin; // 设置上面的 margin
    CGFloat w = wNum * SJItemWH + (wNum - 1) * SJMargin;
    CGFloat h = hNum * SJItemWH + (hNum - 1) * SJMargin;
    
    return CGRectMake(x, y, w, h);
}

- (CGFloat)bottomMarginInCollectionView:(UICollectionView *)collectionView layout:(SJCustomLayout *)layout {
    
    return SJMargin;
}


#pragma mark - UICollectionViewDataSource, UICollectionViewDelegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    // 根据数据量显示或者隐藏footer
    self.collectionView.mj_footer.hidden = (self.dataArray.count == 0);
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SJOneCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([SJOneCell class]) forIndexPath:indexPath];
    
    SJWordItem *item = self.dataArray[indexPath.row];
    
    cell.isChoosing = self.isChoosing;
    cell.isDisplayTitle = self.isDisplayTitle;
    cell.item = item;
    
    WeakSelf;
    cell.singleTapLabel = ^(UICollectionViewCell *cell) {
        
        [weakSelf singleTap:cell];
    };
    
    cell.doubleTapLabel = ^(UICollectionViewCell *cell) {
        
        [weakSelf doubleTap:cell];
    };
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self selectedOrDeselectedItemAtIndexPath:indexPath];
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self selectedOrDeselectedItemAtIndexPath:indexPath];
}

- (void)selectedOrDeselectedItemAtIndexPath:(NSIndexPath*)indexPath {
    
    if ([self.isChoosing isEqualToString:@"0"]) {
        return;
    }
    
    SJWordItem *item = self.dataArray[indexPath.row];
    item.isSelected = !item.isSelected;
    [_collectionView reloadItemsAtIndexPaths:@[indexPath]];
    if (item.isSelected) {
        if (![_selectedArray containsObject:item]) {
            [_selectedArray addObject:item];
        }
    } else {
        if ([_selectedArray containsObject:item]) {
            [_selectedArray removeObject:item];
        };
    }
}

#pragma mark 点击 cell 的事件
- (void)doubleTap:(UICollectionViewCell *)cell {
    
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    
    if (indexPath.row >= self.dataArray.count) {
        return;
    }
    
    SJWordItem *item = self.dataArray[indexPath.row];
    
    if ([item.fmt isEqualToString:@"8"]) {
        return;
    }
    
    
    self.selectedItem = item;
    
    if ([item.fmt isEqualToString:@"1"]) { // 文字
        
        [self tapText:(SJOneCell *)cell item:item];
        
    } else if ([item.fmt isEqualToString:@"2"]) { // 图片
        
        [self tapPic:(SJOneCell *)cell item:item];
        
    } else if ([item.fmt isEqualToString:@"3"]) { // 音频
        
        [self tapAudio:(SJOneCell *)cell item:item];
        
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[@"name"] = @"音频播放";
        attributes[@"content"] = item.content;
        [SJStatisticTool event:@"play_Audio" attributes:attributes];
        
    } else if ([item.fmt isEqualToString:@"4"]) { // 视频
        
        [self tapVideo:(SJOneCell *)cell item:item];
        
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[@"name"] = @"视频播放";
        attributes[@"content"] = item.content;
        [SJStatisticTool event:@"play_Video" attributes:attributes];
        
    } else if ([item.fmt isEqualToString:@"11"]) { // 文本
        
        SJTxtDetailViewController *txtVC = [SJTxtDetailViewController new];
        txtVC.item = item;
        [self.navigationController pushViewController:txtVC animated:YES];
    }
    
    
//    if ([item.fmt isEqualToString:@"1"]) {
//
//        self.selectedItem = item;
//        [self tapText:(SJOneCell *)cell item:item];
//    } else {
//
//        SJTreeViewController *treeVC = [SJTreeViewController new];
//        treeVC.pageType = @"ss";
//        treeVC.item = item;
//        [self.navigationController pushViewController:treeVC animated:YES];
//
//    }
}

- (void)singleTap:(UICollectionViewCell *)cell {
    
    if ([self.isChoosing isEqualToString:@"1"]) {
        return;
    }
    
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    
    if (indexPath.row >= self.dataArray.count) {
        return;
    }
    
    SJWordItem *item = self.dataArray[indexPath.row];
    
    if ([item.fmt isEqualToString:@"8"]) {
        return;
    }
    
    SJTreeViewController *treeVC = [SJTreeViewController new];
    treeVC.pageType = @"ss";
    treeVC.item = item;
    [self.navigationController pushViewController:treeVC animated:YES];
    
//    
//    self.selectedItem = item;
//    
//    if ([item.fmt isEqualToString:@"1"]) { // 文字
//        
//        SJTreeViewController *treeVC = [SJTreeViewController new];
//        treeVC.pageType = @"ss";
//        treeVC.item = item;
//        [self.navigationController pushViewController:treeVC animated:YES];
//        
//    } else if ([item.fmt isEqualToString:@"2"]) { // 图片
//        
//        [self tapPic:(SJOneCell *)cell item:item];
//        
//    } else if ([item.fmt isEqualToString:@"3"]) { // 音频
//        
//        [self tapAudio:(SJOneCell *)cell item:item];
//        
//        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
//        attributes[@"name"] = @"音频播放";
//        attributes[@"content"] = item.content;
//        [SJStatisticTool event:@"play_Audio" attributes:attributes];
//        
//    } else if ([item.fmt isEqualToString:@"4"]) { // 视频
//        
//        [self tapVideo:(SJOneCell *)cell item:item];
//        
//        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
//        attributes[@"name"] = @"视频播放";
//        attributes[@"content"] = item.content;
//        [SJStatisticTool event:@"play_Video" attributes:attributes];
//        
//    } else if ([item.fmt isEqualToString:@"11"]) { // 文本
//        
//        SJTxtDetailViewController *txtVC = [SJTxtDetailViewController new];
//        txtVC.item = item;
//        [self.navigationController pushViewController:txtVC animated:YES];
//    }
}

- (void)tapAudio:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    
    SJExtraItem *extra = [SJExtraItem modelWithJSON:item.extra];
    
    if (extra.cover) {
        NSString *urlString = [NSString stringWithFormat:@"%@%@", SJImgURL, extra.cover];
        imageInfo.imageURL = [NSURL URLWithString:urlString];
    } else {
        UIImage *img = [UIImage imageNamed:@"icn_audio"];
        imageInfo.image = img;
        imageInfo.referenceContentMode = UIViewContentModeCenter;
    }
    
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@", SJAvURL, self.selectedItem.content];
    self.player = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:urlString]];
    [self.player play];
}


- (void)tapVideo:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    imageInfo.referenceContentMode = UIViewContentModeCenter;
    UIImage *img = [UIImage imageNamed:@"common_trans_square"];
    
    imageInfo.image = img;
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    
    // 视频
    [[JPVideoPlayerCache sharedCache] clearDiskOnCompletion:^{
        // do something  必须清了缓存？才能播放？
    }];
    
    self.videoContainer = ({
        UIView *videoView = [UIView new];
        videoView.backgroundColor = [UIColor blackColor];
        videoView.frame = CGRectMake(0, 0, SJScreenW, SJScreenW * 9.0 / 16.0);
        [imageViewer.imageView addSubview:videoView];
        
        videoView;
    });
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
    [self.videoContainer addGestureRecognizer:tapGestureRecognizer];
    self.videoContainer.jp_videoPlayerDelegate = self;
    [self.videoContainer jp_perfersPlayingProgressViewColor:SJColorHexString(@"#f76a4a")];
    [self.videoContainer jp_perfersDownloadProgressViewColor:[UIColor lightGrayColor]];
    NSString *urlString = [NSString stringWithFormat:@"%@%@", SJAvURL, self.selectedItem.content];
    [self.videoContainer jp_playVideoWithURL:[NSURL URLWithString:urlString]];
    
}

- (void)tapText:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = item.content;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.numberOfLines = 0;
    titleLabel.size_sd = CGSizeMake(SJScreenW - SJLayoutFrame(40), SJScreenH);
    
    UIImage *img = [titleLabel.layer snapshotImage];
    while (!img) { // 这样好吗？
        img = [titleLabel.layer snapshotImage];
    }
    
    imageInfo.image = img;
    
    
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    
}

- (void)tapPic:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@", SJImgURL, item.content];
    imageInfo.imageURL = [NSURL URLWithString:urlString];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    imageInfo.referenceCornerRadius = 6;
    
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    
}

#pragma mark - JPVideoPlayerDelegate

- (BOOL)shouldDownloadVideoForURL:(NSURL *)videoURL{
    return YES;
}

- (BOOL)shouldProgressViewOnTop{
    return NO;
}

- (BOOL)shouldAutoReplayAfterPlayCompleteForURL:(nonnull NSURL *)videoURL {
    
    return YES;
}

- (void)playingStatusDidChanged:(JPVideoPlayerPlayingStatus)playingStatus{
    
    SJLog(@"playingStatus-----%ld", (long)playingStatus);
    
}

//- (void)downloadingProgressDidChanged:(CGFloat)downloadingProgress{
//    SJLog(@"downloadingProgress------%0.2lf", downloadingProgress);
//}
//
//- (void)playingProgressDidChanged:(CGFloat)playingProgress{
//    SJLog(@"playingProgress------%0.2lf", playingProgress);
//}

#pragma mark - Tap Event

- (void)handleTapGesture:(UITapGestureRecognizer *)sender {
    if (sender.state == UIGestureRecognizerStateEnded) {
        if (self.videoContainer.viewStatus == JPVideoPlayerVideoViewStatusPortrait) {
            [self.videoContainer jp_gotoLandscapeAnimated:YES completion:^{
            }];
        }
        else if (self.videoContainer.viewStatus == JPVideoPlayerVideoViewStatusLandscape) {
            [self.videoContainer jp_gotoPortraitAnimated:YES completion:^{
            }];
        }
        
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
}

#pragma JTSImageViewControllerAnimationDelegate

- (void)imageViewerWillBeginPresentation:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView {
    
}

- (void)imageViewerWillAnimatePresentation:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView duration:(CGFloat)duration { // 显示完 图片墙 did
    
    WeakSelf;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf showDetaillInView:containerView];
    });
    
    
}

- (void)imageViewer:(JTSImageViewController *)imageViewer willAdjustInterfaceForZoomScale:(CGFloat)zoomScale withContainerView:(UIView *)containerView duration:(CGFloat)duration {
    
}

- (void)imageViewerWillBeginDismissal:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView { // 将要消失 图片墙 will
    
    // 删除详情
    [self hideDetaill];
    
    if ([self.selectedItem.fmt isEqualToString:@"4"]) {
        
        [self.videoContainer jp_stopPlay];
        [self.videoContainer removeFromSuperview];
        self.videoContainer = nil;
    }
    
    if ([self.selectedItem.fmt isEqualToString:@"3"]) {
        
        [self.player pause];
        self.player = nil;
    }
}

- (void)imageViewerWillAnimateDismissal:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView duration:(CGFloat)duration {
    
    
}


- (void)showDetaillInView:(UIView *)view {
    
    [view addSubview:self.detailImageView];
    self.detailImageView.sd_layout
    .heightIs(SJLayoutFrame(45))
    .leftSpaceToView(view, SJLayoutFrame(0))
    .rightSpaceToView(view, SJLayoutFrame(0))
    .bottomSpaceToView(view, SJLayoutFrame(0));
    
    SJExtraItem *extraItem = [SJExtraItem modelWithJSON:self.selectedItem.extra];
    self.detailLabel.text = extraItem.t;
    
    [UIView animateWithDuration:.25 animations:^{
        self.detailImageView.alpha = 1;
    }];
}

- (void)hideDetaill {
    
    [self.detailImageView removeAllSubviews];
    [self.detailImageView removeFromSuperview];
    self.detailImageView = nil;
    self.detailLabel = nil;
    
}

#pragma mark - request

- (void)loadNewData {
    
    if ([self.isChoosing isEqualToString:@"1"]) {
        [self.collectionView.mj_header endRefreshing];
        return;
    }
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"rn"] = SJCountOfPage;
    parameters[@"pn"] = @"0";
    
    SJSpaceStationListApi *api = [[SJSpaceStationListApi alloc] initWithParameters:parameters];
    
    if ([api loadCacheWithError:nil]) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            self.dataArray = [[NSArray modelArrayWithClass:[SJWordItem class] json:api.responseObject[@"content"][@"data"]] mutableCopy];
            self.page = [api.responseObject[@"content"][@"cur"] intValue];
            [self getItemOrigin];
            
        } else {
            [self.dataArray removeAllObjects];
        }
    }
    
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            self.dataArray = [[NSArray modelArrayWithClass:[SJWordItem class] json:api.responseObject[@"content"][@"data"]] mutableCopy];
            self.page = [api.responseObject[@"content"][@"cur"] intValue];
            [self getItemOrigin];
            
        } else {
            [self.dataArray removeAllObjects];
        }
        
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
        
    } failure:^(YTKBaseRequest *request) {
        
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
    }];
    
}

- (void)loadMoreData {
    
    if ([self.isChoosing isEqualToString:@"1"]) {
        [self.collectionView.mj_footer endRefreshing];
        return;
    }
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"rn"] = SJCountOfPage;
    parameters[@"pn"] = [NSString stringWithFormat:@"%d", ++self.page];
    
    SJSpaceStationListApi *api = [[SJSpaceStationListApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            [self.dataArray addObjectsFromArray:[NSArray modelArrayWithClass:[SJWordItem class] json:api.responseObject[@"content"][@"data"]]];
            self.page = [api.responseObject[@"content"][@"cur"] intValue];
            [self getItemOrigin];
            
        } else {
            self.page--;
        }
        
        [self.collectionView reloadData];
        [self.collectionView.mj_footer endRefreshing];
        
    } failure:^(YTKBaseRequest *request) {
        [self.collectionView reloadData];
        [self.collectionView.mj_footer endRefreshing];
        self.page--;
    }];
}


- (void)getItemOrigin {
    
    // 为每个 item 设置 l、t。
    int startT = 0;
    for (SJWordItem *item in self.dataArray) {
        
        item.t = [NSString stringWithFormat:@"%d", startT];
        item.l = @"0";
        
        int h = [item.h intValue];
        startT += h;
    }
}

@end
